<template>
  <el-container style="margin-left: 100px">
    <el-header style="text-align: center"><groupChat style="height: 50px;width:200px"/></el-header>
    <div class="chat-panel">
      <div class="chat-header">
        <div class="user-info">
          <el-avatar :size="40" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" class="user-avatar"></el-avatar>
          <div class="user-details">
            <div class="user-name">世界频道</div>
            <div class="user-status">
              <span class="status-dot online"></span>
              <span class="status-text">在线</span>
            </div>
          </div>
        </div>
        <div class="chat-actions">
          <el-tooltip content="搜索聊天记录" placement="bottom">
            <button class="action-btn"><i class="el-icon-search"></i></button>
          </el-tooltip>
        </div>
      </div>

      <div class="chat-body">
        <div class="messages" ref="messageList">
          <div v-if="messages.length === 0" class="empty-chat">
            <i class="el-icon-chat-dot-round"></i>
            <p>世界频道聊天开始了</p>
          </div>
          
          <div v-for="(message, index) in messages" :key="index" class="message-row" :class="{
            'outgoing': message.from === userEmail,
            'incoming': message.from !== userEmail
          }">
            <div class="avatar-container" v-if="message.from !== userEmail">
              <el-avatar :size="36" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" @click="showUserProfile(message.from)"></el-avatar>
            </div>
            <div class="message">
              <div class="message-time" @click="showUserProfile(message.from)">{{ formatSenderName(message.from) }}</div>
              <div class="message-content">
                <p>{{ message.content }}</p>
              </div>
              <div class="message-status" v-if="message.from === userEmail">
                <i class="el-icon-check"></i>
              </div>
            </div>
            <div class="avatar-container" v-if="message.from === userEmail">
              <el-avatar :size="36" :src="userPicture" @click="showUserProfile(userEmail)"></el-avatar>
            </div>
          </div>
        </div>

        <div class="message-composer">
          <div class="composer-input">
            <el-input
              v-model="newMessage"
              type="textarea"
              :rows="3"
              resize="none"
              placeholder="输入消息..."
              @keyup.enter.native="sendMessage"
            ></el-input>
          </div>
          
          <div class="composer-actions">
            <el-button
              type="primary"
              :disabled="!newMessage.trim()"
              @click="sendMessage"
              class="send-btn"
            >
              <i class="el-icon-position"></i>
              <span>发送</span>
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 用户信息弹窗 -->
      <el-dialog
        title="用户信息"
        :visible.sync="userProfileVisible"
        width="500px"
        custom-class="user-profile-dialog"
        :before-close="handleCloseUserProfile">
        <div v-if="selectedUser" class="user-profile-content">
          <div class="user-profile-header">
            <el-avatar :size="80" :src="selectedUser.userPicture || defaultAvatar"></el-avatar>
            <div class="user-profile-info">
              <h3>{{ selectedUser.userName }}</h3>
              <p>{{ selectedUser.userEmail }}</p>
            </div>
          </div>
          <div class="user-profile-details">
            <div class="detail-item">
              <span class="detail-label">专业：</span>
              <span class="detail-value">{{ getDeptName(selectedUser.dept_id) }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">性别：</span>
              <span class="detail-value">{{  selectedUser.userSex || '未设置'}}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">年龄：</span>
              <span class="detail-value">{{ selectedUser.userAge || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">国籍：</span>
              <span class="detail-value">{{ selectedUser.userFrom || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">个人简介：</span>
              <p class="detail-value">{{ selectedUser.userSelf || '暂无简介' }}</p>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="userProfileVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </div>
  </el-container>
</template>

<script>
import {addGroupMessage, getGroupMessageList, getUserInfo} from "@/api/api";
import GroupChat from "@/components/groupChat.vue";

export default {
  name: "Chat",
  components: {GroupChat},
  computed: {
    userEmail() {
      return this.$store.state.me.userEmail;
    },
    userPicture() {
      return this.$store.state.me.userPicture;
    }
  },
  data() {
    return {
      newMessage: '',
      messages: [],
      loading: false,
      userProfileVisible: false,
      selectedUser: null,
      defaultAvatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    };
  },
  methods: {
    formatSenderName(email) {
      if (email === this.userEmail) {
        return '我';
      }
      return email;
    },
    async sendMessage() {
      if (this.newMessage.trim() !== '') {
        this.loading = true;
        
        this.messages.push({
          from: this.$store.state.me.userEmail,
          content: this.newMessage
        });

        this.$store.state.websocket.send(JSON.stringify({
          type: 'Allmessage',
          message: this.newMessage,
          from: this.$store.state.me.userEmail,
        }));

        const message = this.newMessage;
        this.newMessage = '';

        const response = await addGroupMessage({
          content: message,
        });
        if (response.data.message === "成功") {
          this.scrollToBottom();
        } else {
          this.$message.error("发送信息失败");
          this.messages.pop();
        }
        this.loading = false;
      }
    },
    async InitMessages() {
      try {
        const response = await getGroupMessageList();
        this.messages = response.data.data;
        this.scrollToBottom();
      } catch (error) {
        console.error('Error fetching messages:', error);
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const messageList = this.$refs.messageList;
        if (messageList) {
          messageList.scrollTop = messageList.scrollHeight;
        }
      });
    },
    // 获取部门名称
    getDeptName(deptId) {
      if (!deptId) return '未设置';
      const dept = this.$store.state.deptList.find(dept => dept.dept_id === deptId);
      return dept ? dept.dept_name : '未知部门';
    },
    // 显示用户个人主页
    async showUserProfile(userEmail) {
      if (!userEmail) return;
      
      this.loading = true;
      try {
        const response = await getUserInfo(userEmail);
        if (response.data.message === "成功") {
          this.selectedUser = response.data.data;
          this.userProfileVisible = true;
        } else {
          this.$message.error("获取用户信息失败");
        }
      } catch (error) {
        console.error("获取用户信息出错:", error);
        this.$message.error("获取用户信息出错");
      } finally {
        this.loading = false;
      }
    },
    // 关闭用户个人主页
    handleCloseUserProfile() {
      this.userProfileVisible = false;
      this.selectedUser = null;
    }
  },
  mounted() {
    this.InitMessages();

    // 监听 WebSocket 消息
    this.$store.state.websocket.onmessage = (event) => {
      const message = JSON.parse(event.data);
      this.messages.push({
        from: message.from,
        content: message.content
      });
    };
  },
  watch: {
    messages: {
      deep: true,
      handler() {
        this.scrollToBottom();
      }
    }
  }
}
</script>

<style scoped>
.chat-panel {
  width: 80%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  border: none;
  background: radial-gradient(ellipse farthest-side at 76% 77%, rgba(245, 228, 212, 0.25) 4%, rgba(255, 255, 255, 0) calc(4% + 1px)), radial-gradient(circle at 76% 40%, #fef6ec 4%, rgba(255, 255, 255, 0) 4.18%), linear-gradient(135deg, #ff0000 0%, #000036 100%), radial-gradient(ellipse at 28% 0%, #ffcfac 0%, rgba(98, 149, 144, 0.5) 100%), linear-gradient(180deg, #cd6e8a 0%, #f5eab0 69%, #d6c8a2 70%, #a2758d 100%);
  background-blend-mode: normal, normal, screen, overlay, normal;
  box-shadow: 0px 0px 10px 1px #000000;
}

.chat-header {
  padding: 12px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dadce0;
  background-color: white;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  border: 2px solid #e8f0fe;
}

.user-details {
  margin-left: 12px;
}

.user-name {
  font-weight: 500;
  color: #202124;
  font-size: 16px;
}

.user-status {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #5f6368;
  margin-top: 2px;
}

.status-dot {
  height: 8px;
  width: 8px;
  border-radius: 50%;
  margin-right: 5px;
}

.status-dot.online {
  background-color: #34a853;
}

.chat-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: none;
  background-color: transparent;
  color: #5f6368;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.action-btn:hover {
  background-color: #f1f3f4;
}

.action-btn i {
  font-size: 18px;
}

.chat-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
  position: relative;
  overflow: hidden;
  padding-bottom: 30px;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
}

.empty-chat {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #5f6368;
}

.empty-chat i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #dadce0;
}

.message-row {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-end;
}

.incoming {
  justify-content: flex-start;
}

.outgoing {
  justify-content: flex-end;
}

.avatar-container {
  margin: 0 8px;
}

.message {
  display: flex;
  flex-direction: column;
  max-width: 65%;
}

.incoming .message {
  align-items: flex-start;
}

.outgoing .message {
  align-items: flex-end;
}

.message-time {
  font-size: 11px;
  color: #5f6368;
  margin-bottom: 4px;
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  box-shadow: 0 1px 2px rgba(60, 64, 67, 0.15);
}

.incoming .message-content {
  background-color: white;
  border-top-left-radius: 4px;
  color: #202124;
}

.outgoing .message-content {
  background-color: #1a73e8;
  border-top-right-radius: 4px;
  color: white;
}

.message-content p {
  margin: 0;
  line-height: 1.4;
  font-size: 15px;
  white-space: pre-wrap;
  word-break: break-word;
}

.message-status {
  font-size: 12px;
  color: #34a853;
  margin-top: 4px;
}

.message-composer {
  padding: 16px;
  padding-bottom: 30px;
  background-color: white;
  border-top: 1px solid #dadce0;
  position: relative;
  bottom: 16px;
  margin-bottom: -16px;
}

.composer-input {
  margin-bottom: 12px;
  margin-top: 16px;
}

.composer-input >>> .el-textarea__inner {
  border-radius: 8px;
  border: 1px solid #dadce0;
  padding: 12px;
  font-size: 15px;
  transition: all 0.2s;
}

.composer-input >>> .el-textarea__inner:focus {
  border-color: #1a73e8;
  box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}

.composer-actions {
  display: flex;
  justify-content: flex-end;
}

.send-btn {
  border-radius: 24px;
  background-color: #1a73e8;
  border: none;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.2s;
}

.send-btn:hover:not(:disabled) {
  background-color: #1765c9;
  transform: translateY(-1px);
}

.send-btn:disabled {
  background-color: #dadce0;
  color: #9aa0a6;
}

.send-btn i {
  margin-right: 6px;
}

/* 用户个人主页弹窗样式 */
.user-profile-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.user-profile-dialog :deep(.el-dialog__header) {
  background-color: #f0f2f7;
  padding: 16px 20px;
  border-bottom: 1px solid #e0e5ef;
}

.user-profile-dialog :deep(.el-dialog__title) {
  font-weight: 600;
  color: #333;
}

.user-profile-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.user-profile-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.user-profile-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.user-profile-info h3 {
  margin: 0 0 4px 0;
  font-size: 18px;
  color: #333;
}

.user-profile-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.user-profile-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-item {
  display: flex;
}

.detail-label {
  width: 80px;
  font-weight: 500;
  color: #666;
}

.detail-value {
  flex: 1;
  color: #333;
}

/* 添加鼠标悬停效果 */
.avatar-container .el-avatar, .message-time {
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-container .el-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.message-time:hover {
  color: #1a73e8;
  text-decoration: underline;
}
</style>
